<template>
    <ul class="list">
        <li 
            class="item" 
            v-for='item of letters' 
            :key="item"
            :ref='item'
            @touchstart='handleTouchStart'
            @touchmove='handleTouchMove'
            @touchend='handleTouchEnd'
            @click='handleLetterClick'
        >
            {{item}}
        </li>
    </ul>
</template>

<script>
export default {
    name: "CityAlphabet",
    props: {
        cities: Object
    },
    data () {
        return {
            // 定义一个是否能上下拖动的状态量
            touchStatus: false,
            // 把运行时固定的量提出来，优化性能
            startY: 0,
            timer: null
        }
    },
    updated () {
        //记录A所在的‘纵坐标’ 距离自身‘框架’
        this.startY = this.$refs['A'][0].offsetTop
    },
    computed: {
        // 定义一个字母表的数组（由object转化）（注意用的是‘in’,得到的是键值 字母
        letters () {
            const letters = []
            for (let i in this.cities) {
                letters.push(i)
            }
            return letters
        }
    },
    methods: {
        handleLetterClick(e){
            // 向外触发事件 由父组件监听
            this.$emit('change', e.target.innerText)
            // console.log(e.target.innerText)
        },
        handleTouchStart(e){
            this.touchStatus = true
        },
        handleTouchMove(e){
            if (this.touchStatus) {
                if (this.timer) {
                    clearTimeout(this.timer)
                }
                // 性能优化，降低触发频率节流 设置一个16毫秒的延时重置
                this.timer = setTimeout(() => {
                    //触碰点的‘纵坐标’ 要减去上端的header长度
                    const touchY = e.touches[0].clientY - 79
                    const index = Math.floor((touchY - this.startY) / 20)
                    if (index >= 0 && index < this.letters.length){
                        this.$emit('change', this.letters[index])
                    }
                }, 8)
                
                
            }
        },
        handleTouchEnd(e){
            this.touchStatus = false
        }

    }
}
</script>

<style lang='stylus' scoped>
    @import '~styles/varibles.styl'
    .list
        display: flex
        flex-direction: column
        justify-content: center
        position:  absolute
        top: 1.58rem
        right: 0
        bottom: 0
        width: .4rem
        .item
            line-height: .4rem
            text-align: center
            color: $bgColor
</style>